package cn.edu.zut.soft.graduate.topicCenter.handler;

import cn.edu.zut.soft.graduate.core.constant.InfoType;
import cn.edu.zut.soft.graduate.core.constant.IssuePhase;
import cn.edu.zut.soft.graduate.core.constant.IssueSource;
import cn.edu.zut.soft.graduate.core.constant.Role;
import cn.edu.zut.soft.graduate.core.constant.config.IKEY;
import cn.edu.zut.soft.graduate.core.model.Impl.Group;
import cn.edu.zut.soft.graduate.core.model.Impl.Info;
import cn.edu.zut.soft.graduate.core.model.Impl.Issue;
import cn.edu.zut.soft.graduate.core.vo.LoginVO;
import cn.edu.zut.soft.graduate.core.vo.UserDescVO;
import cn.edu.zut.soft.graduate.groupCenter.bo.GroupBO;
import cn.edu.zut.soft.graduate.topicCenter.bo.DeclareBO;
import cn.edu.zut.soft.graduate.userCenter.bo.IdentityBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Arrays;
import java.util.List;

import static cn.edu.zut.soft.graduate.core.constant.IssuePhase.Handle.AuditGiveUp;
import static cn.edu.zut.soft.graduate.core.constant.IssuePhase.Handle.SaveIngGiveUp;

/**
 * @author cc
 * @Date 2016/11/21
 * @value 1.0
 */

/**
 * 保存中到失效 拒绝之后失效的情况
 */
@Component
public class ChangeToGiveUp extends ChangeToAuditOK {

    private List<IssuePhase.Handle> handleList = Arrays.asList(SaveIngGiveUp, AuditGiveUp);

    @Autowired
    private DeclareBO declareBO;

    @Autowired
    private GroupBO groupBO;

    @Autowired
    private IdentityBO identityBO;


    @Override
    protected boolean conform(LoginVO loginVO, Issue issue, IssuePhase.Handle handle) {
        return handleList.contains(handle);
    }

    @Override
    @Transactional
    protected void conformChange(LoginVO loginVO, Issue issue, IssuePhase.Handle handle) {
        //自拟题目的失效处理
        if (issue.getIdentityRole() == Role.stu) {
            //小组校外转校内
            //小组长
            UserDescVO author = identityBO.userPersonal(issue.getIdentityId());
            Integer groupId = null;
            for (Info info : author.getInfoList()) {
                if (InfoType.Group.name().equals(info.getType()) && IKEY.GROUP.equals(info.getKey())) {
                    groupId = Integer.parseInt(info.getValue());
                }
            }
            //小组从校外转校内
            Assert.notNull(groupId,"小组不存在,请联系管理员");
            Group group = groupBO.get(groupId);
            group.setStatus(IssueSource.school);
            groupBO.update(group, loginVO.getName());
            declareBO.deleteByGroupId(groupId, loginVO.getName());

            //删除申请记录
        }
        issue.setDel(-1);
        //判断是否失效,失效时同时逻辑删除
//        issue.setStatus(handle.getDst());
        issue.addStatus(handle.getDst());
        //优化性能,去除大对象的修改
        issue.setContent(null);
    }
}
